using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SeataNet.Core.Common;
using SeataNet.Core.Monitor;
using SeataNet.Core.RPC;
using SeataNet.Core.Transaction;

namespace SeataNet.Core.Cluster
{
    /// <summary>
    /// 集群协调器接口
    /// </summary>
    public interface IClusterCoordinator
    {
        /// <summary>
        /// 启动协调器
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>任务</returns>
        Task StartAsync(CancellationToken cancellationToken);

        /// <summary>
        /// 停止协调器
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>任务</returns>
        Task StopAsync(CancellationToken cancellationToken);

        /// <summary>
        /// 协调全局事务
        /// </summary>
        /// <param name="globalTransaction">全局事务</param>
        /// <returns>任务</returns>
        Task<GlobalTransactionResult> CoordinateGlobalTransactionAsync(GlobalTransaction globalTransaction);

        /// <summary>
        /// 协调分支事务
        /// </summary>
        /// <param name="branchTransaction">分支事务</param>
        /// <param name="operation">操作类型</param>
        /// <returns>任务</returns>
        Task<BranchTransactionResult> CoordinateBranchTransactionAsync(BranchTransaction branchTransaction, BranchOperation operation);

        /// <summary>
        /// 处理事务状态变更
        /// </summary>
        /// <param name="transactionId">事务ID</param>
        /// <param name="status">新状态</param>
        /// <returns>任务</returns>
        Task HandleTransactionStatusChangeAsync(string transactionId, Common.TransactionStatus status);

        /// <summary>
        /// 处理节点故障
        /// </summary>
        /// <param name="nodeId">节点ID</param>
        /// <returns>任务</returns>
        Task HandleNodeFailureAsync(string nodeId);

        /// <summary>
        /// 处理节点恢复
        /// </summary>
        /// <param name="nodeId">节点ID</param>
        /// <returns>任务</returns>
        Task HandleNodeRecoveryAsync(string nodeId);

        /// <summary>
        /// 获取协调器状态
        /// </summary>
        /// <returns>协调器状态</returns>
        CoordinatorStatus GetStatus();

        /// <summary>
        /// 获取协调器统计信息
        /// </summary>
        /// <returns>协调器统计信息</returns>
        CoordinatorStatistics GetStatistics();
    }

    /// <summary>
    /// 全局事务结果
    /// </summary>
    public class GlobalTransactionResult
    {
        /// <summary>
        /// 事务ID
        /// </summary>
        public string TransactionId { get; set; } = string.Empty;

        /// <summary>
        /// 结果状态
        /// </summary>
        public Common.TransactionStatus Status { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string? ErrorMessage { get; set; }

        /// <summary>
        /// 执行时间（毫秒）
        /// </summary>
        public long ExecutionTimeMs { get; set; }

        /// <summary>
        /// 参与节点列表
        /// </summary>
        public List<string> ParticipantNodes { get; set; } = new List<string>();

        /// <summary>
        /// 成功的分支事务数
        /// </summary>
        public int SuccessfulBranches { get; set; }

        /// <summary>
        /// 失败的分支事务数
        /// </summary>
        public int FailedBranches { get; set; }

        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess => Status == TransactionStatus.Committed || Status == TransactionStatus.RolledBack;
    }

    /// <summary>
    /// 分支事务结果
    /// </summary>
    public class BranchTransactionResult
    {
        /// <summary>
        /// 分支事务ID
        /// </summary>
        public string BranchId { get; set; } = string.Empty;

        /// <summary>
        /// 全局事务ID
        /// </summary>
        public string GlobalTransactionId { get; set; } = string.Empty;

        /// <summary>
        /// 结果状态
        /// </summary>
        public BranchStatus Status { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string? ErrorMessage { get; set; }

        /// <summary>
        /// 执行时间（毫秒）
        /// </summary>
        public long ExecutionTimeMs { get; set; }

        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess => Status == BranchStatus.PhaseOneDone || Status == BranchStatus.PhaseTwoCommitted || Status == BranchStatus.PhaseTwoRollbacked;
    }

    /// <summary>
    /// 全局事务
    /// </summary>
    public class GlobalTransaction
    {
        /// <summary>
        /// 事务ID
        /// </summary>
        public string TransactionId { get; set; } = string.Empty;

        /// <summary>
        /// 事务名称
        /// </summary>
        public string TransactionName { get; set; } = string.Empty;

        /// <summary>
        /// 事务类型
        /// </summary>
        public Common.TransactionType TransactionType { get; set; }

        /// <summary>
        /// 超时时间（毫秒）
        /// </summary>
        public int Timeout { get; set; }

        /// <summary>
        /// 事务状态
        /// </summary>
        public Common.TransactionStatus Status { get; set; }

        /// <summary>
        /// 应用ID
        /// </summary>
        public string ApplicationId { get; set; } = string.Empty;

        /// <summary>
        /// 事务服务组
        /// </summary>
        public string TransactionServiceGroup { get; set; } = string.Empty;

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime BeginTime { get; set; }

        /// <summary>
        /// 应用数据
        /// </summary>
        public string? ApplicationData { get; set; }
    }
    
    /// <summary>
    /// 分支事务
    /// </summary>
    public class BranchTransaction
    {
        /// <summary>
        /// 分支事务ID
        /// </summary>
        public long BranchId { get; set; }

        /// <summary>
        /// 全局事务ID
        /// </summary>
        public string Xid { get; set; } = string.Empty;

        /// <summary>
        /// 全局事务ID（别名）
        /// </summary>
        public string GlobalTransactionId
        {
            get => Xid;
            set => Xid = value;
        }

        /// <summary>
        /// 分支类型
        /// </summary>
        public BranchType BranchType { get; set; }

        /// <summary>
        /// 资源ID
        /// </summary>
        public string ResourceId { get; set; } = string.Empty;

        /// <summary>
        /// 锁键
        /// </summary>
        public string LockKey { get; set; } = string.Empty;

        /// <summary>
        /// 应用数据
        /// </summary>
        public string? ApplicationData { get; set; }
    }

    /// <summary>
    /// 分支操作类型
    /// </summary>
    public enum BranchOperation
    {
        /// <summary>
        /// 注册
        /// </summary>
        Register,

        /// <summary>
        /// 提交
        /// </summary>
        Commit,

        /// <summary>
        /// 回滚
        /// </summary>
        Rollback,

        /// <summary>
        /// 查询状态
        /// </summary>
        QueryStatus
    }

    /// <summary>
    /// 协调器状态
    /// </summary>
    public enum CoordinatorStatus
    {
        /// <summary>
        /// 未启动
        /// </summary>
        NotStarted,

        /// <summary>
        /// 启动中
        /// </summary>
        Starting,

        /// <summary>
        /// 运行中
        /// </summary>
        Running,

        /// <summary>
        /// 停止中
        /// </summary>
        Stopping,

        /// <summary>
        /// 已停止
        /// </summary>
        Stopped,

        /// <summary>
        /// 错误
        /// </summary>
        Error
    }

    /// <summary>
    /// 协调器统计信息
    /// </summary>
    public class CoordinatorStatistics
    {
        /// <summary>
        /// 协调的全局事务总数
        /// </summary>
        public long TotalGlobalTransactions { get; set; }

        /// <summary>
        /// 协调的分支事务总数
        /// </summary>
        public long TotalBranchTransactions { get; set; }

        /// <summary>
        /// 成功的全局事务数
        /// </summary>
        public long SuccessfulGlobalTransactions { get; set; }

        /// <summary>
        /// 失败的全局事务数
        /// </summary>
        public long FailedGlobalTransactions { get; set; }

        /// <summary>
        /// 成功的分支事务数
        /// </summary>
        public long SuccessfulBranchTransactions { get; set; }

        /// <summary>
        /// 失败的分支事务数
        /// </summary>
        public long FailedBranchTransactions { get; set; }

        /// <summary>
        /// 平均协调时间（毫秒）
        /// </summary>
        public double AverageCoordinationTimeMs { get; set; }

        /// <summary>
        /// 最大协调时间（毫秒）
        /// </summary>
        public long MaxCoordinationTimeMs { get; set; }

        /// <summary>
        /// 最小协调时间（毫秒）
        /// </summary>
        public long MinCoordinationTimeMs { get; set; }

        /// <summary>
        /// 处理的节点故障数
        /// </summary>
        public long HandledNodeFailures { get; set; }

        /// <summary>
        /// 处理的节点恢复数
        /// </summary>
        public long HandledNodeRecoveries { get; set; }

        /// <summary>
        /// 当前活跃事务数
        /// </summary>
        public long ActiveTransactions { get; set; }

        /// <summary>
        /// 启动时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 最后更新时间
        /// </summary>
        public DateTime LastUpdateTime { get; set; }
    }

    /// <summary>
    /// 默认集群协调器实现
    /// </summary>
    public class DefaultClusterCoordinator : IClusterCoordinator
    {
        private readonly ILogger<DefaultClusterCoordinator> _logger;
        private readonly IClusterManager _clusterManager;
        private readonly ILoadBalancer _loadBalancer;
        private readonly IFailoverManager _failoverManager;
        private readonly ITransactionManager _transactionManager;
        private readonly ITransactionMonitor _transactionMonitor;
        private readonly IOptionsMonitor<ClusterConfiguration> _configuration;
        private readonly SemaphoreSlim _coordinationSemaphore = new SemaphoreSlim(1, 1);
        private readonly ConcurrentDictionary<string, GlobalTransaction> _activeGlobalTransactions = new ConcurrentDictionary<string, GlobalTransaction>();
        private readonly ConcurrentDictionary<string, List<BranchTransaction>> _branchTransactions = new ConcurrentDictionary<string, List<BranchTransaction>>();
        private CoordinatorStatus _status = CoordinatorStatus.NotStarted;
        private CoordinatorStatistics _statistics = new CoordinatorStatistics();
        private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        public DefaultClusterCoordinator(
            ILogger<DefaultClusterCoordinator> logger,
            IClusterManager clusterManager,
            ILoadBalancer loadBalancer,
            IFailoverManager failoverManager,
            ITransactionManager transactionManager,
            ITransactionMonitor transactionMonitor,
            IOptionsMonitor<ClusterConfiguration> configuration)
        {
            _logger = logger;
            _clusterManager = clusterManager;
            _loadBalancer = loadBalancer;
            _failoverManager = failoverManager;
            _transactionManager = transactionManager;
            _transactionMonitor = transactionMonitor;
            _configuration = configuration;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            if (_status != CoordinatorStatus.NotStarted)
            {
                _logger.LogWarning("Cluster coordinator is already started or starting");
                return;
            }

            _status = CoordinatorStatus.Starting;
            _logger.LogInformation("Starting cluster coordinator");

            try
            {
                // 初始化统计信息
                _statistics.StartTime = DateTime.UtcNow;
                _statistics.LastUpdateTime = DateTime.UtcNow;

                // 启动协调循环
                _ =  Task.Run(CoordinationLoopAsync, _cancellationTokenSource.Token);

                _status = CoordinatorStatus.Running;
                _logger.LogInformation("Cluster coordinator started successfully");
            }
            catch (Exception ex)
            {
                _status = CoordinatorStatus.Error;
                _logger.LogError(ex, "Error starting cluster coordinator");
                throw;
            }
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            if (_status != CoordinatorStatus.Running)
            {
                _logger.LogWarning("Cluster coordinator is not running");
                return;
            }

            _status = CoordinatorStatus.Stopping;
            _logger.LogInformation("Stopping cluster coordinator");

            try
            {
                // 取消所有正在进行的操作
                _cancellationTokenSource.Cancel();

                // 等待协调循环结束
                await Task.Delay(1000, cancellationToken);

                _status = CoordinatorStatus.Stopped;
                _logger.LogInformation("Cluster coordinator stopped successfully");
            }
            catch (Exception ex)
            {
                _status = CoordinatorStatus.Error;
                _logger.LogError(ex, "Error stopping cluster coordinator");
            }
        }

        public async Task<GlobalTransactionResult> CoordinateGlobalTransactionAsync(GlobalTransaction globalTransaction)
        {
            if (_status != CoordinatorStatus.Running)
            {
                return new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = TransactionStatus.Finished,
                    ErrorMessage = "Coordinator is not running",
                    ExecutionTimeMs = 0
                };
            }

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                await _coordinationSemaphore.WaitAsync(_cancellationTokenSource.Token);

                // 记录活跃事务
                _activeGlobalTransactions[globalTransaction.TransactionId] = globalTransaction;

                // 监控事务开始
                _transactionMonitor.RecordTransaction(globalTransaction.TransactionId, TransactionStatus.Begin);

                // 根据事务类型执行不同的协调逻辑
                GlobalTransactionResult result;
                switch (globalTransaction.TransactionType)
                {
                    case TransactionType.AT:
                        result = await CoordinateAtTransactionAsync(globalTransaction);
                        break;
                    case TransactionType.TCC:
                        result = await CoordinateTccTransactionAsync(globalTransaction);
                        break;
                    case TransactionType.Saga:
                        result = await CoordinateSagaTransactionAsync(globalTransaction);
                        break;
                    case TransactionType.XA:
                        result = await CoordinateXaTransactionAsync(globalTransaction);
                        break;
                    default:
                        result = new GlobalTransactionResult
                        {
                            TransactionId = globalTransaction.TransactionId,
                            Status = TransactionStatus.Finished,
                            ErrorMessage = $"Unsupported transaction type: {globalTransaction.TransactionType}",
                            ExecutionTimeMs = stopwatch.ElapsedMilliseconds
                        };
                        break;
                }

                // 更新统计信息
                UpdateStatistics(result, stopwatch.ElapsedMilliseconds);

                // 移除活跃事务
                _activeGlobalTransactions.TryRemove(globalTransaction.TransactionId, out _);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error coordinating global transaction {TransactionId}", globalTransaction.TransactionId);

                var result = new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = TransactionStatus.Finished,
                    ErrorMessage = ex.Message,
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds
                };

                // 更新统计信息
                UpdateStatistics(result, stopwatch.ElapsedMilliseconds);

                // 移除活跃事务
                _activeGlobalTransactions.TryRemove(globalTransaction.TransactionId, out _);

                return result;
            }
            finally
            {
                _coordinationSemaphore.Release();
                stopwatch.Stop();
            }
        }

        public async Task<BranchTransactionResult> CoordinateBranchTransactionAsync(BranchTransaction branchTransaction, BranchOperation operation)
        {
            if (_status != CoordinatorStatus.Running)
            {
                return new BranchTransactionResult
                {
                    BranchId = branchTransaction.BranchId.ToString(),
                    GlobalTransactionId = branchTransaction.GlobalTransactionId,
                    Status = BranchStatus.PhaseOneFailed,
                    ErrorMessage = "Coordinator is not running",
                    ExecutionTimeMs = 0
                };
            }

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                // 根据操作类型执行不同的协调逻辑
                BranchTransactionResult result;
                switch (operation)
                {
                    case BranchOperation.Register:
                        result = await RegisterBranchTransactionAsync(branchTransaction);
                        break;
                    case BranchOperation.Commit:
                        result = await CommitBranchTransactionAsync(branchTransaction);
                        break;
                    case BranchOperation.Rollback:
                        result = await RollbackBranchTransactionAsync(branchTransaction);
                        break;
                    case BranchOperation.QueryStatus:
                        result = await QueryBranchTransactionStatusAsync(branchTransaction);
                        break;
                    default:
                        result = new BranchTransactionResult
                        {
                            BranchId = branchTransaction.BranchId.ToString(),
                            GlobalTransactionId = branchTransaction.GlobalTransactionId,
                            Status = BranchStatus.PhaseOneFailed,
                            ErrorMessage = $"Unsupported branch operation: {operation}",
                            ExecutionTimeMs = stopwatch.ElapsedMilliseconds
                        };
                        break;
                }

                // 更新统计信息
                UpdateBranchStatistics(result, stopwatch.ElapsedMilliseconds);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error coordinating branch transaction {BranchId}", branchTransaction.BranchId);

                var result = new BranchTransactionResult
                {
                    BranchId = branchTransaction.BranchId.ToString(),
                    GlobalTransactionId = branchTransaction.GlobalTransactionId,
                    Status = BranchStatus.PhaseOneFailed,
                    ErrorMessage = ex.Message,
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds
                };

                // 更新统计信息
                UpdateBranchStatistics(result, stopwatch.ElapsedMilliseconds);

                return result;
            }
            finally
            {
                stopwatch.Stop();
            }
        }

        public async Task HandleTransactionStatusChangeAsync(string transactionId, Common.TransactionStatus status)
        {
            if (_status != CoordinatorStatus.Running)
            {
                return;
            }

            try
            {
                _logger.LogInformation("Handling transaction status change: {TransactionId} -> {Status}", transactionId, status);

                // 监控事务状态变更
                _transactionMonitor.RecordTransaction(transactionId, status);

                // 如果事务完成，从活跃事务列表中移除
                if (status == TransactionStatus.Committed || status == TransactionStatus.RolledBack || status == TransactionStatus.Finished)
                {
                    _activeGlobalTransactions.TryRemove(transactionId, out _);
                }

                // 如果有分支事务，也需要处理
                if (_branchTransactions.TryGetValue(transactionId, out var branches))
                {
                    foreach (var branch in branches)
                    {
                        var branchStatus = status switch
                        {
                            TransactionStatus.Committed => BranchStatus.PhaseTwoCommitted,
                            TransactionStatus.RolledBack => BranchStatus.PhaseTwoRollbacked,
                            TransactionStatus.Finished => BranchStatus.Failed,
                            _ => BranchStatus.Unknown
                        };

                        _transactionMonitor.RecordBranch(branch.BranchId, branchStatus);
                    }
                }

                _logger.LogInformation("Transaction status change handled: {TransactionId} -> {Status}", transactionId, status);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error handling transaction status change: {TransactionId} -> {Status}", transactionId, status);
            }
        }

        public async Task HandleNodeFailureAsync(string nodeId)
        {
            if (_status != CoordinatorStatus.Running)
            {
                return;
            }

            try
            {
                _logger.LogInformation("Handling node failure: {NodeId}", nodeId);

                // 获取节点上的活跃事务
                var nodeTransactions = GetActiveTransactionsOnNode(nodeId);

                // 对每个事务执行故障转移
                foreach (var transaction in nodeTransactions)
                {
                    await HandleTransactionNodeFailureAsync(transaction, nodeId);
                }

                // 更新统计信息
                _statistics.HandledNodeFailures++;

                _logger.LogInformation("Node failure handled: {NodeId}", nodeId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error handling node failure: {NodeId}", nodeId);
            }
        }

        public async Task HandleNodeRecoveryAsync(string nodeId)
        {
            if (_status != CoordinatorStatus.Running)
            {
                return;
            }

            try
            {
                _logger.LogInformation("Handling node recovery: {NodeId}", nodeId);

                // 重新同步节点状态
                await ResyncNodeStateAsync(nodeId);

                // 更新统计信息
                _statistics.HandledNodeRecoveries++;

                _logger.LogInformation("Node recovery handled: {NodeId}", nodeId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error handling node recovery: {NodeId}", nodeId);
            }
        }

        public CoordinatorStatus GetStatus()
        {
            return _status;
        }

        public CoordinatorStatistics GetStatistics()
        {
            _statistics.ActiveTransactions = _activeGlobalTransactions.Count;
            _statistics.LastUpdateTime = DateTime.UtcNow;
            return _statistics;
        }

        private async Task CoordinationLoopAsync()
        {
            _logger.LogInformation("Starting coordination loop");

            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                try
                {
                    // 定期检查活跃事务状态
                    await CheckActiveTransactionsAsync();

                    // 定期清理已完成的事务
                    await CleanupCompletedTransactionsAsync();

                    // 等待下一次检查
                    await Task.Delay(5000, _cancellationTokenSource.Token);
                }
                catch (OperationCanceledException)
                {
                    // 正常取消，退出循环
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error in coordination loop");
                }
            }

            _logger.LogInformation("Coordination loop stopped");
        }

        private async Task<GlobalTransactionResult> CoordinateAtTransactionAsync(GlobalTransaction globalTransaction)
        {
            // AT事务协调逻辑（两阶段提交）
            // 阶段1：各分支执行业务SQL，记录undo log
            // 阶段2：协调器决定提交或回滚

            _logger.LogInformation("Coordinating AT transaction: {TransactionId}", globalTransaction.TransactionId);

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var participantNodes = new List<string>();
            var successfulBranches = 0;
            var failedBranches = 0;

            try
            {
                // 1. 开始全局事务
                var xid = await _transactionManager.BeginAsync(
                    timeout: globalTransaction.Timeout,
                    name: globalTransaction.TransactionName);

                if (string.IsNullOrEmpty(xid))
                {
                    _logger.LogError("Failed to begin global transaction for {TransactionId}", globalTransaction.TransactionId);
                    return new GlobalTransactionResult
                    {
                        TransactionId = globalTransaction.TransactionId,
                        Status = TransactionStatus.Finished,
                        ErrorMessage = "Failed to begin global transaction",
                        ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                        SuccessfulBranches = 0,
                        FailedBranches = 0
                    };
                }

                _logger.LogInformation("Global transaction started: {Xid}", xid);

                // 2. 获取该全局事务的所有分支事务
                if (!_branchTransactions.TryGetValue(globalTransaction.TransactionId, out var branches))
                {
                    branches = new List<BranchTransaction>();
                }

                _logger.LogInformation("Found {Count} branch transactions for global transaction {Xid}", branches.Count, xid);

                // 3. 第一阶段：等待所有分支完成（实际环境中分支会异步注册）
                // 这里假设分支已经注册并执行完成
                var phaseOneSuccess = true;
                var phaseOneErrors = new List<string>();

                foreach (var branch in branches)
                {
                    try
                    {
                        // 检查分支状态
                        var branchStatus = await _transactionManager.GetBranchStatusAsync(xid, branch.BranchId);

                        if (branchStatus == BranchStatus.PhaseOneDone || branchStatus == BranchStatus.Registered)
                        {
                            successfulBranches++;
                            if (!string.IsNullOrEmpty(branch.ResourceId) && !participantNodes.Contains(branch.ResourceId))
                            {
                                participantNodes.Add(branch.ResourceId);
                            }
                            _logger.LogInformation("Branch {BranchId} phase one completed successfully", branch.BranchId);
                        }
                        else
                        {
                            phaseOneSuccess = false;
                            failedBranches++;
                            var error = $"Branch {branch.BranchId} phase one failed with status {branchStatus}";
                            phaseOneErrors.Add(error);
                            _logger.LogError(error);
                        }
                    }
                    catch (Exception ex)
                    {
                        phaseOneSuccess = false;
                        failedBranches++;
                        var error = $"Error checking branch {branch.BranchId}: {ex.Message}";
                        phaseOneErrors.Add(error);
                        _logger.LogError(ex, "Error checking branch {BranchId}", branch.BranchId);
                    }
                }

                // 4. 第二阶段：根据第一阶段结果决定提交或回滚
                TransactionStatus finalStatus;
                string? errorMessage = null;

                if (phaseOneSuccess && failedBranches == 0)
                {
                    // 所有分支第一阶段成功，执行提交
                    _logger.LogInformation("All branches phase one completed, committing global transaction {Xid}", xid);

                    try
                    {
                        var commitSuccess = await _transactionManager.CommitAsync(xid);

                        if (commitSuccess)
                        {
                            finalStatus = TransactionStatus.Committed;
                            _logger.LogInformation("Global transaction {Xid} committed successfully", xid);

                            // 通知各分支提交（AT模式下通常是异步删除undo log）
                            foreach (var branch in branches)
                            {
                                try
                                {
                                    await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                    _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogWarning(ex, "Failed to report branch {BranchId} commit status", branch.BranchId);
                                }
                            }
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            errorMessage = "Global transaction commit failed";
                            _logger.LogError("Global transaction {Xid} commit failed", xid);
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"Commit error: {ex.Message}";
                        _logger.LogError(ex, "Error committing global transaction {Xid}", xid);
                    }
                }
                else
                {
                    // 有分支失败，执行回滚
                    _logger.LogWarning("Some branches failed, rolling back global transaction {Xid}. Errors: {Errors}",
                        xid, string.Join("; ", phaseOneErrors));

                    try
                    {
                        var rollbackSuccess = await _transactionManager.RollbackAsync(xid);

                        if (rollbackSuccess)
                        {
                            finalStatus = TransactionStatus.RolledBack;
                            errorMessage = phaseOneErrors.Count > 0 ? string.Join("; ", phaseOneErrors) : "Transaction rolled back";
                            _logger.LogInformation("Global transaction {Xid} rolled back successfully", xid);

                            // 通知各分支回滚（AT模式下执行undo log恢复数据）
                            foreach (var branch in branches)
                            {
                                try
                                {
                                    await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                                    _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogWarning(ex, "Failed to report branch {BranchId} rollback status", branch.BranchId);
                                }
                            }
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            errorMessage = $"Rollback failed. Phase one errors: {string.Join("; ", phaseOneErrors)}";
                            _logger.LogError("Global transaction {Xid} rollback failed", xid);
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"Rollback error: {ex.Message}. Phase one errors: {string.Join("; ", phaseOneErrors)}";
                        _logger.LogError(ex, "Error rolling back global transaction {Xid}", xid);
                    }
                }

                stopwatch.Stop();

                var result = new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = finalStatus,
                    ErrorMessage = errorMessage,
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };

                // 记录事务监控
                _transactionMonitor.RecordTransaction(xid, finalStatus);

                _logger.LogInformation(
                    "AT transaction coordination completed: {Xid}, Status: {Status}, Duration: {Duration}ms, Successful: {Successful}, Failed: {Failed}",
                    xid, finalStatus, stopwatch.ElapsedMilliseconds, successfulBranches, failedBranches);

                return result;
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                _logger.LogError(ex, "Unexpected error coordinating AT transaction {TransactionId}", globalTransaction.TransactionId);

                return new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = TransactionStatus.Finished,
                    ErrorMessage = $"Coordination error: {ex.Message}",
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };
            }
        }

        private async Task<GlobalTransactionResult> CoordinateTccTransactionAsync(GlobalTransaction globalTransaction)
        {
            // TCC事务协调逻辑（三阶段提交）
            // Try阶段：尝试执行并预留资源
            // Confirm阶段：确认执行
            // Cancel阶段：取消执行，释放资源

            _logger.LogInformation("Coordinating TCC transaction: {TransactionId}", globalTransaction.TransactionId);

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var participantNodes = new List<string>();
            var successfulBranches = 0;
            var failedBranches = 0;

            try
            {
                // 1. 开始全局事务
                var xid = await _transactionManager.BeginAsync(
                    timeout: globalTransaction.Timeout,
                    name: globalTransaction.TransactionName);

                if (string.IsNullOrEmpty(xid))
                {
                    return new GlobalTransactionResult
                    {
                        TransactionId = globalTransaction.TransactionId,
                        Status = TransactionStatus.Finished,
                        ErrorMessage = "Failed to begin TCC transaction",
                        ExecutionTimeMs = stopwatch.ElapsedMilliseconds
                    };
                }

                // 2. 获取分支事务
                if (!_branchTransactions.TryGetValue(globalTransaction.TransactionId, out var branches))
                {
                    branches = new List<BranchTransaction>();
                }

                // 3. Try阶段：检查所有分支的Try执行结果
                var trySuccess = true;
                var tryErrors = new List<string>();

                foreach (var branch in branches)
                {
                    try
                    {
                        var branchStatus = await _transactionManager.GetBranchStatusAsync(xid, branch.BranchId);

                        if (branchStatus == BranchStatus.PhaseOneDone || branchStatus == BranchStatus.Registered)
                        {
                            successfulBranches++;
                            if (!string.IsNullOrEmpty(branch.ResourceId))
                            {
                                participantNodes.Add(branch.ResourceId);
                            }
                            _logger.LogInformation("Branch {BranchId} Try phase completed successfully", branch.BranchId);
                        }
                        else
                        {
                            trySuccess = false;
                            failedBranches++;
                            tryErrors.Add($"Branch {branch.BranchId} Try phase failed with status {branchStatus}");
                        }
                    }
                    catch (Exception ex)
                    {
                        trySuccess = false;
                        failedBranches++;
                        tryErrors.Add($"Error in Try phase for branch {branch.BranchId}: {ex.Message}");
                        _logger.LogError(ex, "Error in Try phase for branch {BranchId}", branch.BranchId);
                    }
                }

                // 4. Confirm或Cancel阶段
                TransactionStatus finalStatus;
                string? errorMessage = null;

                if (trySuccess && failedBranches == 0)
                {
                    // Try成功，执行Confirm
                    _logger.LogInformation("All branches Try phase completed, executing Confirm for {Xid}", xid);

                    try
                    {
                        var commitSuccess = await _transactionManager.CommitAsync(xid);

                        if (commitSuccess)
                        {
                            finalStatus = TransactionStatus.Committed;

                            // 通知各分支执行Confirm
                            foreach (var branch in branches)
                            {
                                try
                                {
                                    await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                    _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogWarning(ex, "Failed to report branch {BranchId} Confirm status", branch.BranchId);
                                }
                            }
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            errorMessage = "TCC Confirm phase failed";
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"Confirm error: {ex.Message}";
                        _logger.LogError(ex, "Error in Confirm phase for {Xid}", xid);
                    }
                }
                else
                {
                    // Try失败，执行Cancel
                    _logger.LogWarning("Some branches Try phase failed, executing Cancel for {Xid}", xid);

                    try
                    {
                        var rollbackSuccess = await _transactionManager.RollbackAsync(xid);

                        if (rollbackSuccess)
                        {
                            finalStatus = TransactionStatus.RolledBack;
                            errorMessage = string.Join("; ", tryErrors);

                            // 通知各分支执行Cancel
                            foreach (var branch in branches)
                            {
                                try
                                {
                                    await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                                    _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogWarning(ex, "Failed to report branch {BranchId} Cancel status", branch.BranchId);
                                }
                            }
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            errorMessage = $"Cancel failed. Try errors: {string.Join("; ", tryErrors)}";
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"Cancel error: {ex.Message}";
                        _logger.LogError(ex, "Error in Cancel phase for {Xid}", xid);
                    }
                }

                var result = new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = finalStatus,
                    ErrorMessage = errorMessage,
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };

                _transactionMonitor.RecordTransaction(xid, finalStatus);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unexpected error coordinating TCC transaction {TransactionId}", globalTransaction.TransactionId);

                return new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = TransactionStatus.Finished,
                    ErrorMessage = $"Coordination error: {ex.Message}",
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };
            }
        }

        private async Task<GlobalTransactionResult> CoordinateSagaTransactionAsync(GlobalTransaction globalTransaction)
        {
            // Saga事务协调逻辑（补偿模式）
            // 正向执行：按顺序执行各个步骤
            // 补偿执行：如果失败，按相反顺序执行补偿操作

            _logger.LogInformation("Coordinating Saga transaction: {TransactionId}", globalTransaction.TransactionId);

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var participantNodes = new List<string>();
            var successfulBranches = 0;
            var failedBranches = 0;

            try
            {
                // 1. 开始全局事务
                var xid = await _transactionManager.BeginAsync(
                    timeout: globalTransaction.Timeout,
                    name: globalTransaction.TransactionName);

                if (string.IsNullOrEmpty(xid))
                {
                    return new GlobalTransactionResult
                    {
                        TransactionId = globalTransaction.TransactionId,
                        Status = TransactionStatus.Finished,
                        ErrorMessage = "Failed to begin Saga transaction",
                        ExecutionTimeMs = stopwatch.ElapsedMilliseconds
                    };
                }

                // 2. 获取Saga步骤（分支事务）
                if (!_branchTransactions.TryGetValue(globalTransaction.TransactionId, out var branches))
                {
                    branches = new List<BranchTransaction>();
                }

                _logger.LogInformation("Found {Count} Saga steps for transaction {Xid}", branches.Count, xid);

                // 3. 正向执行阶段：检查所有步骤的执行结果
                var forwardSuccess = true;
                var forwardErrors = new List<string>();
                var completedSteps = new List<BranchTransaction>();

                foreach (var branch in branches.OrderBy(b => b.BranchId))  // 按顺序执行
                {
                    try
                    {
                        var branchStatus = await _transactionManager.GetBranchStatusAsync(xid, branch.BranchId);

                        if (branchStatus == BranchStatus.PhaseOneDone || branchStatus == BranchStatus.Registered)
                        {
                            successfulBranches++;
                            completedSteps.Add(branch);
                            if (!string.IsNullOrEmpty(branch.ResourceId))
                            {
                                participantNodes.Add(branch.ResourceId);
                            }
                            _logger.LogInformation("Saga step {BranchId} completed successfully", branch.BranchId);
                        }
                        else
                        {
                            forwardSuccess = false;
                            failedBranches++;
                            forwardErrors.Add($"Saga step {branch.BranchId} failed with status {branchStatus}");
                            _logger.LogError("Saga step {BranchId} failed, will trigger compensation", branch.BranchId);
                            break;  // Saga失败时停止后续步骤的执行
                        }
                    }
                    catch (Exception ex)
                    {
                        forwardSuccess = false;
                        failedBranches++;
                        forwardErrors.Add($"Error in Saga step {branch.BranchId}: {ex.Message}");
                        _logger.LogError(ex, "Error in Saga step {BranchId}", branch.BranchId);
                        break;
                    }
                }

                // 4. 决定提交或补偿
                TransactionStatus finalStatus;
                string? errorMessage = null;

                if (forwardSuccess && failedBranches == 0)
                {
                    // 所有步骤成功，提交事务
                    _logger.LogInformation("All Saga steps completed successfully, committing transaction {Xid}", xid);

                    try
                    {
                        var commitSuccess = await _transactionManager.CommitAsync(xid);

                        if (commitSuccess)
                        {
                            finalStatus = TransactionStatus.Committed;

                            // 通知各步骤完成
                            foreach (var branch in completedSteps)
                            {
                                try
                                {
                                    await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                    _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogWarning(ex, "Failed to report Saga step {BranchId} completion", branch.BranchId);
                                }
                            }
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            errorMessage = "Saga commit failed";
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"Commit error: {ex.Message}";
                        _logger.LogError(ex, "Error committing Saga transaction {Xid}", xid);
                    }
                }
                else
                {
                    // 有步骤失败，执行补偿（按相反顺序）
                    _logger.LogWarning("Saga forward execution failed, executing compensation for {Xid}", xid);

                    try
                    {
                        var compensationSuccess = true;
                        var compensationErrors = new List<string>();

                        // 按相反顺序执行补偿操作
                        foreach (var branch in completedSteps.OrderByDescending(b => b.BranchId))
                        {
                            try
                            {
                                _logger.LogInformation("Executing compensation for Saga step {BranchId}", branch.BranchId);

                                // 通知分支执行补偿
                                await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                                _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                            }
                            catch (Exception ex)
                            {
                                compensationSuccess = false;
                                compensationErrors.Add($"Compensation failed for step {branch.BranchId}: {ex.Message}");
                                _logger.LogError(ex, "Error executing compensation for Saga step {BranchId}", branch.BranchId);
                            }
                        }

                        var rollbackSuccess = await _transactionManager.RollbackAsync(xid);

                        if (rollbackSuccess && compensationSuccess)
                        {
                            finalStatus = TransactionStatus.RolledBack;
                            errorMessage = string.Join("; ", forwardErrors);
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            var allErrors = forwardErrors.Concat(compensationErrors);
                            errorMessage = $"Compensation incomplete: {string.Join("; ", allErrors)}";
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"Compensation error: {ex.Message}";
                        _logger.LogError(ex, "Error executing compensation for Saga {Xid}", xid);
                    }
                }

                var result = new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = finalStatus,
                    ErrorMessage = errorMessage,
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };

                _transactionMonitor.RecordTransaction(xid, finalStatus);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unexpected error coordinating Saga transaction {TransactionId}", globalTransaction.TransactionId);

                return new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = TransactionStatus.Finished,
                    ErrorMessage = $"Coordination error: {ex.Message}",
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };
            }
        }

        private async Task<GlobalTransactionResult> CoordinateXaTransactionAsync(GlobalTransaction globalTransaction)
        {
            // XA事务协调逻辑（标准XA两阶段提交）
            // 阶段1：XA PREPARE - 所有资源管理器准备提交
            // 阶段2：XA COMMIT/ROLLBACK - 协调器决定最终提交或回滚

            _logger.LogInformation("Coordinating XA transaction: {TransactionId}", globalTransaction.TransactionId);

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var participantNodes = new List<string>();
            var successfulBranches = 0;
            var failedBranches = 0;

            try
            {
                // 1. 开始全局事务
                var xid = await _transactionManager.BeginAsync(
                    timeout: globalTransaction.Timeout,
                    name: globalTransaction.TransactionName);

                if (string.IsNullOrEmpty(xid))
                {
                    return new GlobalTransactionResult
                    {
                        TransactionId = globalTransaction.TransactionId,
                        Status = TransactionStatus.Finished,
                        ErrorMessage = "Failed to begin XA transaction",
                        ExecutionTimeMs = stopwatch.ElapsedMilliseconds
                    };
                }

                // 2. 获取所有XA分支
                if (!_branchTransactions.TryGetValue(globalTransaction.TransactionId, out var branches))
                {
                    branches = new List<BranchTransaction>();
                }

                _logger.LogInformation("Found {Count} XA branches for transaction {Xid}", branches.Count, xid);

                // 3. XA PREPARE阶段：检查所有资源管理器是否准备好提交
                var prepareSuccess = true;
                var prepareErrors = new List<string>();

                foreach (var branch in branches)
                {
                    try
                    {
                        var branchStatus = await _transactionManager.GetBranchStatusAsync(xid, branch.BranchId);

                        // XA PREPARE成功的状态
                        if (branchStatus == BranchStatus.PhaseOneDone || branchStatus == BranchStatus.Registered)
                        {
                            successfulBranches++;
                            if (!string.IsNullOrEmpty(branch.ResourceId))
                            {
                                participantNodes.Add(branch.ResourceId);
                            }
                            _logger.LogInformation("XA branch {BranchId} prepared successfully (resource: {ResourceId})",
                                branch.BranchId, branch.ResourceId);
                        }
                        else
                        {
                            prepareSuccess = false;
                            failedBranches++;
                            prepareErrors.Add($"XA branch {branch.BranchId} prepare failed with status {branchStatus}");
                            _logger.LogError("XA branch {BranchId} prepare failed", branch.BranchId);
                        }
                    }
                    catch (Exception ex)
                    {
                        prepareSuccess = false;
                        failedBranches++;
                        prepareErrors.Add($"Error preparing XA branch {branch.BranchId}: {ex.Message}");
                        _logger.LogError(ex, "Error preparing XA branch {BranchId}", branch.BranchId);
                    }
                }

                // 4. XA COMMIT/ROLLBACK阶段
                TransactionStatus finalStatus;
                string? errorMessage = null;

                if (prepareSuccess && failedBranches == 0)
                {
                    // 所有分支PREPARE成功，执行XA COMMIT
                    _logger.LogInformation("All XA branches prepared, executing XA COMMIT for {Xid}", xid);

                    try
                    {
                        var commitSuccess = await _transactionManager.CommitAsync(xid);

                        if (commitSuccess)
                        {
                            finalStatus = TransactionStatus.Committed;
                            _logger.LogInformation("XA transaction {Xid} committed successfully", xid);

                            // 通知各分支执行XA COMMIT
                            foreach (var branch in branches)
                            {
                                try
                                {
                                    await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                    _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoCommitted);
                                    _logger.LogInformation("XA branch {BranchId} committed", branch.BranchId);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogWarning(ex, "Failed to report XA branch {BranchId} commit status", branch.BranchId);
                                }
                            }
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            errorMessage = "XA COMMIT failed";
                            _logger.LogError("XA transaction {Xid} commit failed", xid);
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"XA COMMIT error: {ex.Message}";
                        _logger.LogError(ex, "Error committing XA transaction {Xid}", xid);
                    }
                }
                else
                {
                    // 有分支PREPARE失败，执行XA ROLLBACK
                    _logger.LogWarning("Some XA branches prepare failed, executing XA ROLLBACK for {Xid}. Errors: {Errors}",
                        xid, string.Join("; ", prepareErrors));

                    try
                    {
                        var rollbackSuccess = await _transactionManager.RollbackAsync(xid);

                        if (rollbackSuccess)
                        {
                            finalStatus = TransactionStatus.RolledBack;
                            errorMessage = string.Join("; ", prepareErrors);
                            _logger.LogInformation("XA transaction {Xid} rolled back successfully", xid);

                            // 通知各分支执行XA ROLLBACK
                            foreach (var branch in branches)
                            {
                                try
                                {
                                    await _transactionManager.ReportBranchStatusAsync(xid, branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                                    _transactionMonitor.RecordBranch(branch.BranchId, BranchStatus.PhaseTwoRollbacked);
                                    _logger.LogInformation("XA branch {BranchId} rolled back", branch.BranchId);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogWarning(ex, "Failed to report XA branch {BranchId} rollback status", branch.BranchId);
                                }
                            }
                        }
                        else
                        {
                            finalStatus = TransactionStatus.Failed;
                            errorMessage = $"XA ROLLBACK failed. Prepare errors: {string.Join("; ", prepareErrors)}";
                            _logger.LogError("XA transaction {Xid} rollback failed", xid);
                        }
                    }
                    catch (Exception ex)
                    {
                        finalStatus = TransactionStatus.Failed;
                        errorMessage = $"XA ROLLBACK error: {ex.Message}";
                        _logger.LogError(ex, "Error rolling back XA transaction {Xid}", xid);
                    }
                }

                stopwatch.Stop();

                var result = new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = finalStatus,
                    ErrorMessage = errorMessage,
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };

                _transactionMonitor.RecordTransaction(xid, finalStatus);

                _logger.LogInformation(
                    "XA transaction coordination completed: {Xid}, Status: {Status}, Duration: {Duration}ms, Successful: {Successful}, Failed: {Failed}",
                    xid, finalStatus, stopwatch.ElapsedMilliseconds, successfulBranches, failedBranches);

                return result;
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                _logger.LogError(ex, "Unexpected error coordinating XA transaction {TransactionId}", globalTransaction.TransactionId);

                return new GlobalTransactionResult
                {
                    TransactionId = globalTransaction.TransactionId,
                    Status = TransactionStatus.Finished,
                    ErrorMessage = $"Coordination error: {ex.Message}",
                    ExecutionTimeMs = stopwatch.ElapsedMilliseconds,
                    ParticipantNodes = participantNodes,
                    SuccessfulBranches = successfulBranches,
                    FailedBranches = failedBranches
                };
            }
        }

        private async Task<BranchTransactionResult> RegisterBranchTransactionAsync(BranchTransaction branchTransaction)
        {
            _logger.LogInformation("Registering branch transaction: {BranchId}", branchTransaction.BranchId);

            // 添加到分支事务列表
            if (!_branchTransactions.TryGetValue(branchTransaction.GlobalTransactionId, out var branches))
            {
                branches = new List<BranchTransaction>();
                _branchTransactions[branchTransaction.GlobalTransactionId] = branches;
            }
            branches.Add(branchTransaction);

            // 监控分支事务
            _transactionMonitor.RecordBranch(branchTransaction.BranchId, BranchStatus.Registered);

            var result = new BranchTransactionResult
            {
                BranchId = branchTransaction.BranchId.ToString(),
                GlobalTransactionId = branchTransaction.GlobalTransactionId,
                Status = BranchStatus.PhaseOneDone,
                ExecutionTimeMs = 0
            };

            return result;
        }

        private async Task<BranchTransactionResult> CommitBranchTransactionAsync(BranchTransaction branchTransaction)
        {
            _logger.LogInformation("Committing branch transaction: {BranchId}", branchTransaction.BranchId);

            // 监控分支事务
            _transactionMonitor.RecordBranch(branchTransaction.BranchId, BranchStatus.PhaseTwoCommitted);

            var result = new BranchTransactionResult
            {
                BranchId = branchTransaction.BranchId.ToString(),
                GlobalTransactionId = branchTransaction.GlobalTransactionId,
                Status = BranchStatus.PhaseTwoCommitted,
                ExecutionTimeMs = 0
            };

            return result;
        }

        private async Task<BranchTransactionResult> RollbackBranchTransactionAsync(BranchTransaction branchTransaction)
        {
            _logger.LogInformation("Rolling back branch transaction: {BranchId}", branchTransaction.BranchId);

            // 监控分支事务
            _transactionMonitor.RecordBranch(branchTransaction.BranchId, BranchStatus.PhaseTwoRollbacked);

            var result = new BranchTransactionResult
            {
                BranchId = branchTransaction.BranchId.ToString(),
                GlobalTransactionId = branchTransaction.GlobalTransactionId,
                Status = BranchStatus.PhaseTwoRollbacked,
                ExecutionTimeMs = 0
            };

            return result;
        }

        private async Task<BranchTransactionResult> QueryBranchTransactionStatusAsync(BranchTransaction branchTransaction)
        {
            _logger.LogInformation("Querying branch transaction status: {BranchId}", branchTransaction.BranchId);

            // 这里简化实现，实际需要查询真实状态
            var result = new BranchTransactionResult
            {
                BranchId = branchTransaction.BranchId.ToString(),
                GlobalTransactionId = branchTransaction.GlobalTransactionId,
                Status = BranchStatus.PhaseOneDone,
                ExecutionTimeMs = 0
            };

            return result;
        }

        private List<GlobalTransaction> GetActiveTransactionsOnNode(string nodeId)
        {
            // 获取节点上的活跃事务
            // 这里简化实现，实际需要根据事务的参与者信息过滤
            return _activeGlobalTransactions.Values.ToList();
        }

        private async Task HandleTransactionNodeFailureAsync(GlobalTransaction transaction, string nodeId)
        {
            _logger.LogInformation("Handling transaction node failure: {TransactionId} on {NodeId}", transaction.TransactionId, nodeId);

            // 根据事务类型和状态执行不同的故障处理逻辑
            // 这里简化实现，实际需要更复杂的故障处理逻辑
        }

        private async Task ResyncNodeStateAsync(string nodeId)
        {
            _logger.LogInformation("Resyncing node state: {NodeId}", nodeId);

            // 重新同步节点状态
            // 这里简化实现，实际需要与节点通信获取最新状态
        }

        private async Task CheckActiveTransactionsAsync()
        {
            // 检查活跃事务状态
            foreach (var transaction in _activeGlobalTransactions.Values)
            {
                try
                {
                    // 查询事务状态
                    var status = await _transactionManager.GetStatusAsync(transaction.TransactionId);

                    // 如果状态变更，处理变更
                    if (status != transaction.Status.GetHashCode())
                    {
                        await HandleTransactionStatusChangeAsync(transaction.TransactionId, (Common.TransactionStatus)status);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error checking transaction status: {TransactionId}", transaction.TransactionId);
                }
            }
        }

        private async Task CleanupCompletedTransactionsAsync()
        {
            // 清理已完成的事务
            var completedTransactions = _activeGlobalTransactions
                .Where(kvp => kvp.Value.Status == TransactionStatus.Committed ||
                              kvp.Value.Status == TransactionStatus.RolledBack ||
                              kvp.Value.Status == TransactionStatus.Finished)
                .Select(kvp => kvp.Key)
                .ToList();

            foreach (var transactionId in completedTransactions)
            {
              
                _branchTransactions.TryRemove(transactionId, out _);
            }
        }

        private void UpdateStatistics(GlobalTransactionResult result, long executionTimeMs)
        {
            if (result.IsSuccess)
            {
                _statistics.SuccessfulGlobalTransactions++;
            }
            else
            {
                _statistics.FailedGlobalTransactions++;
            }

            // 更新协调时间统计
            _statistics.TotalGlobalTransactions++;
            _statistics.AverageCoordinationTimeMs =
                (_statistics.AverageCoordinationTimeMs * (_statistics.TotalGlobalTransactions - 1) + executionTimeMs) /
                _statistics.TotalGlobalTransactions;

            if (executionTimeMs > _statistics.MaxCoordinationTimeMs)
            {
                _statistics.MaxCoordinationTimeMs = executionTimeMs;
            }

            if (_statistics.MinCoordinationTimeMs == 0 || executionTimeMs < _statistics.MinCoordinationTimeMs)
            {
                _statistics.MinCoordinationTimeMs = executionTimeMs;
            }
        }

        private void UpdateBranchStatistics(BranchTransactionResult result, long executionTimeMs)
        {
            _statistics.TotalBranchTransactions++;

            if (result.IsSuccess)
            {
                _statistics.SuccessfulBranchTransactions++;
            }
            else
            {
                _statistics.FailedBranchTransactions++;
            }
        }
    }
}